package web

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path/filepath"
	"testPaper/response"
	"time"
)

// UploadImg 上传图片
func UploadImg(c *gin.Context) {
	// 单文件
	fileHeader, err := c.FormFile("file")
	//判断上传的文件
	if err != nil {
		response.Reponse(c, http.StatusUnprocessableEntity, 422, nil, "上传文件错误")
		return
	}
	//判断后缀为图片的文件
	fileExt := filepath.Ext(fileHeader.Filename)
	if fileExt == ".jpg" || fileExt == ".png" || fileExt == ".gif" || fileExt == ".jpeg" {
		fileDir := fmt.Sprintf("./UploadImg")
		err = os.MkdirAll(fileDir, os.ModePerm)
		if err != nil {
			response.Reponse(c, http.StatusUnprocessableEntity, 422, nil, "上传文件错误")
			return
		}

		//设置图片名字
		timeStamp := time.Now().Unix()
		fileName := fmt.Sprintf("%d%v", timeStamp, fileExt)
		filePathStr := filepath.Join(fileDir, string(fileName))
		//创建文件夹和图片
		c.SaveUploadedFile(fileHeader, filePathStr)
		response.Reponse(c, http.StatusOK, 200, gin.H{"headerImg": filePathStr}, "上传成功")

	} else {
		response.Reponse(c, http.StatusUnprocessableEntity, 422, gin.H{"fileExt": fileExt}, "上传文件错误，头像只支持图片格式")
		return
	}
}
